/*
 * Copyright (c) 2013-2015 SimaStudio. All rights reserved.
 *
 * This software is the confidential and proprietary information of SimaStudio.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with SimaStudio.
 *
 * SimaStudio MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * SimaStudio SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package com.asiainfo.integration.task;

import com.asiainfo.integration.utils.ConfigProvider;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import static java.lang.System.in;

/**
 * Usage: 样例
 *
 * @author Charkey
 * @date 2015/6/22 21:13
 */
@Component
public class DevAutoKCUTask implements Job {

    private static final Logger LOGGER = LoggerFactory.getLogger(DevAutoKCUTask.class);

    private static final String initialContextFactory_Dev = "com.tibco.tibjms.naming.TibjmsInitialContextFactory";
    private static final String connectionUrl_Dev = "tcp://10.144.96.157:7222";
    private static final String username_Dev = "verisuser";
    private static final String password_Dev = "verisuser";
    private static final String connectionFactory_CSO = "VERISO2AQueueConnectionFactory";
    private static final String connectionFactory_KCU = "VERISO2AQueueConnectionFactory";
    private static final String queueName_CSO = "RIL4G.FUL.ServiceOrderManagement.createServiceOrder.Veris.Out.Q.V01";
    private static final String queueName_KCU = "RIL4G.FUL.ServiceOrderManagement.receiveStatusUpdate.Veris.In.Q.V01";

    private Cache createServiceOrderDataCache;

    @Autowired
    public DevAutoKCUTask(CacheManager cacheManager) {
        this.createServiceOrderDataCache = cacheManager.getCache("createServiceOrderDataCache");
    }
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            Hashtable<String, String> environment = new Hashtable<String, String>();
            environment.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory_Dev);
            environment.put(Context.PROVIDER_URL, connectionUrl_Dev);
            environment.put(Context.SECURITY_PRINCIPAL, username_Dev);
            environment.put(Context.SECURITY_CREDENTIALS, password_Dev);
            InitialContext ctx = new InitialContext(environment);
            ConnectionFactory factory_cso = (ConnectionFactory) ctx.lookup(connectionFactory_CSO);
            Connection connection_cso = factory_cso.createConnection(username_Dev, password_Dev);
            Session session_cso = connection_cso.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
            Destination destination_cso = session_cso.createQueue(queueName_CSO);
            connection_cso.start();
            MessageConsumer msgConsumer = session_cso.createConsumer(destination_cso);
            TextMessage textMsg = (TextMessage) msgConsumer.receiveNoWait();
            if (textMsg != null) {
                String text = textMsg.getText();

                QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(connectionFactory_KCU);
                Connection connection = factory.createConnection(username_Dev, password_Dev);
                Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
                Queue queue = session.createQueue(queueName_KCU);

                MessageProducer sender = session.createProducer(queue);
                TextMessage messageToSend = session.createTextMessage();
                messageToSend.setText("MESSAGE CONTENT TO BE SET");
                sender.send(messageToSend);
                sender.close();
                session.commit();

            }



            session_cso.close();
            connection_cso.stop();
        } catch (JMSException e) {
            LOGGER.error("JMSException: " + e.getMessage());
        } catch (NamingException e) {
            LOGGER.error("NamingException: " + e.getMessage());
        }
    }

    private void extractCsoDataToCache(String csoMessage) {
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = builder.parse(csoMessage);
            XPath xpath = XPathFactory.newInstance().newXPath();
            String orderNumberExpression = "/CreateServiceOrderRequest/orderHeader/orderNumber";
            Node orderNumberNode = (Node) xpath.evaluate(orderNumberExpression, document, XPathConstants.NODE);
            System.out.println(orderNumberNode.getTextContent());

            String channelExpression = "/CreateServiceOrderRequest/orderHeader/channel";
            Node channelNode = (Node) xpath.evaluate(orderNumberExpression, document, XPathConstants.NODE);
            System.out.println(channelNode.getTextContent());

        } catch (SAXException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        try {
            URL url = ConfigProvider.class.getClassLoader().getResource("config/task/createServiceOrder.xml");
            InputStream in = new FileInputStream(new File(url.toURI().getPath()));
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = builder.parse(in);
            XPath xpath = XPathFactory.newInstance().newXPath();

            Map<String, String> csoDataMap = new HashMap<String, String>();

            csoDataMap.put("orderNumber", ((Node) xpath.evaluate(XMLConstants.orderNumber, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("channel", ((Node) xpath.evaluate(XMLConstants.channel, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("orderVersion", ((Node) xpath.evaluate(XMLConstants.orderVersion, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("orderRefNumber", ((Node) xpath.evaluate(XMLConstants.orderRefNumber, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("orderType", ((Node) xpath.evaluate(XMLConstants.orderType, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("originatorURI", ((Node) xpath.evaluate(XMLConstants.originatorURI, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("circleID", ((Node) xpath.evaluate(XMLConstants.circleID, document, XPathConstants.NODE)).getTextContent());

            csoDataMap.put("agentId", ((Node) xpath.evaluate(XMLConstants.agentId, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("customerID", ((Node) xpath.evaluate(XMLConstants.customerID, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("customerType", ((Node) xpath.evaluate(XMLConstants.customerType, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("BSSOfferCorrelationID", ((Node) xpath.evaluate(XMLConstants.BSSOfferCorrelationID, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("offerID", ((Node) xpath.evaluate(XMLConstants.offerID, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("businessInteraction_offer", ((Node) xpath.evaluate(XMLConstants.businessInteraction_offer, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("accountID", ((Node) xpath.evaluate(XMLConstants.accountID, document, XPathConstants.NODE)).getTextContent());

            NodeList productCountNodes = (NodeList) xpath.evaluate(XMLConstants.productCount, document, XPathConstants.NODESET);
            // for every product
            for (int i = 0; i < productCountNodes.getLength(); i++) {

            }

            csoDataMap.put("productID", ((Node) xpath.evaluate(XMLConstants.productID, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("BSSProductCorrelationID", ((Node) xpath.evaluate(XMLConstants.BSSProductCorrelationID, document, XPathConstants.NODE)).getTextContent());
            csoDataMap.put("businessInteraction_product", ((Node) xpath.evaluate(XMLConstants.businessInteraction_product, document, XPathConstants.NODE)).getTextContent());
            NodeList serviceIdNodes = (NodeList) xpath.evaluate(XMLConstants.service_id, document, XPathConstants.NODESET);
            for (int i = 0; i < serviceIdNodes.getLength(); i++) {
                csoDataMap.put("service_id_" + i, serviceIdNodes.item(i).getTextContent());
            }
            NodeList serviceNameNodes = (NodeList) xpath.evaluate(XMLConstants.service_name, document, XPathConstants.NODESET);
            for (int i = 0; i < serviceNameNodes.getLength(); i++) {
                csoDataMap.put("service_name_" + i, serviceNameNodes.item(i).getTextContent());
            }
            NodeList serviceTypeNodes = (NodeList) xpath.evaluate(XMLConstants.service_type, document, XPathConstants.NODESET);
            for (int i = 0; i < serviceTypeNodes.getLength(); i++) {
                csoDataMap.put("service_type_" + i, serviceTypeNodes.item(i).getTextContent());
            }
            NodeList serviceBusinessInteractionNodes = (NodeList) xpath.evaluate(XMLConstants.service_businessInteraction, document, XPathConstants.NODESET);
            for (int i = 0; i < serviceBusinessInteractionNodes.getLength(); i++) {
                csoDataMap.put("service_businessInteraction_" + i, serviceBusinessInteractionNodes.item(i).getTextContent());
            }

            NodeList identifierNameNodes = (NodeList) xpath.evaluate(XMLConstants.identifier_name, document, XPathConstants.NODESET);
            for (int i = 0; i < identifierNameNodes.getLength(); i++) {
                csoDataMap.put("identifier_name_" + i, identifierNameNodes.item(i).getTextContent());
            }
            NodeList identifierValueNodes = (NodeList) xpath.evaluate(XMLConstants.identifier_value, document, XPathConstants.NODESET);
            for (int i = 0; i < identifierValueNodes.getLength(); i++) {
                csoDataMap.put("identifier_value" + i, identifierValueNodes.item(i).getTextContent());
            }
            NodeList identifierCategoryNodes = (NodeList) xpath.evaluate(XMLConstants.identifier_category, document, XPathConstants.NODESET);
            for (int i = 0; i < identifierCategoryNodes.getLength(); i++) {
                csoDataMap.put("identifier_category_" + i, identifierCategoryNodes.item(i).getTextContent());
            }
            NodeList identifierSubCategoryNodes = (NodeList) xpath.evaluate(XMLConstants.identifier_subCategory, document, XPathConstants.NODESET);
            for (int i = 0; i < identifierSubCategoryNodes.getLength(); i++) {
                csoDataMap.put("identifier_subCategory_" + i, identifierSubCategoryNodes.item(i).getTextContent());
            }
            NodeList resourceBoqTypeNodes = (NodeList) xpath.evaluate(XMLConstants.resource_boqType, document, XPathConstants.NODESET);
            for (int i = 0; i < resourceBoqTypeNodes.getLength(); i++) {
                csoDataMap.put("resource_boqType_" + i, resourceBoqTypeNodes.item(i).getTextContent());
            }
            NodeList resourceBoqCodeNodes = (NodeList) xpath.evaluate(XMLConstants.resource_boqCode, document, XPathConstants.NODESET);
            for (int i = 0; i < resourceBoqCodeNodes.getLength(); i++) {
                csoDataMap.put("resource_boqCode_" + i, resourceBoqCodeNodes.item(i).getTextContent());
            }
            NodeList resourceIsInstallationRequiredNodes = (NodeList) xpath.evaluate(XMLConstants.resource_isInstallationRequired, document, XPathConstants.NODESET);
            for (int i = 0; i < resourceIsInstallationRequiredNodes.getLength(); i++) {
                csoDataMap.put("resource_isInstallationRequired_" + i, resourceIsInstallationRequiredNodes.item(i).getTextContent());
            }
            NodeList resourceIsManagableNodes = (NodeList) xpath.evaluate(XMLConstants.resource_isManagable, document, XPathConstants.NODESET);
            for (int i = 0; i < resourceIsManagableNodes.getLength(); i++) {
                csoDataMap.put("resource_isManagable_" + i, resourceIsManagableNodes.item(i).getTextContent());
            }
            NodeList resourceBusinessInteractionNodes = (NodeList) xpath.evaluate(XMLConstants.resource_businessInteraction, document, XPathConstants.NODESET);
            for (int i = 0; i < resourceBusinessInteractionNodes.getLength(); i++) {
                csoDataMap.put("resource_businessInteraction_" + i, resourceBusinessInteractionNodes.item(i).getTextContent());
            }
            NodeList resourceQuantityNodes = (NodeList) xpath.evaluate(XMLConstants.resource_quantity, document, XPathConstants.NODESET);
            for (int i = 0; i < resourceQuantityNodes.getLength(); i++) {
                csoDataMap.put("resource_quantity_" + i, resourceQuantityNodes.item(i).getTextContent());
            }

            System.out.println(csoDataMap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }
}
